package com.bnzjy.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bnzjy.srb.core.listener.ExcelDictDTOListener;
import com.bnzjy.srb.core.pojo.dto.ExcelDictDTO;
import com.bnzjy.srb.core.pojo.entity.Dict;
import com.bnzjy.srb.core.mapper.DictMapper;
import com.bnzjy.srb.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2021-12-13
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    
    @Resource
    RedisTemplate redisTemplate;
    
    /**
     * 监听器实例
     * @param inputStream
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void importData(InputStream inputStream) {
        // 这里需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(baseMapper)).sheet().doRead();
    }
    
    /**
     * 客户端请求，导出excel数据
     * @return
     */
    @Override
    public List listDictData() {
        List<Dict> dictList = baseMapper.selectList(null);
        //创建ExcelDictDTO列表，将Dict列表转换成ExcelDictDTO列表
        ArrayList<ExcelDictDTO> excelDictDTOList = new ArrayList<>(dictList.size());
        dictList.forEach(dict -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, excelDictDTO);
            excelDictDTOList.add(excelDictDTO);
        });
        return excelDictDTOList;
    }
    
    /**
     * 根据父id，查询当前节点的子id
     * @param parentId
     * @return
     */
    @Override
    public List<Dict> listByParentId(Long parentId) {
    
//        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
//        dictQueryWrapper.eq("parent_id", parentId);
//        List<Dict> dictList = baseMapper.selectList(dictQueryWrapper);
//        // 填充 hasChildren 字段
//        dictList.forEach(dict -> {
//            //如果有子节点，则是非叶子节点
//            // 判断当前节点是否有子节点，找到当前的 dict 下级有没有子节点
//            boolean hasChildren = this.hasChildren(dict.getId());
//            dict.setHasChildren(hasChildren);
//        });
//        return dictList;
        // 先查询redis中是否存在数据列表
        List<Dict> dictList = null;
        try {
            dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dictList" + parentId);
            if (dictList != null) {
                log.info("从redis中获取");
                return dictList;
            }
        } catch (Exception e) {
            //此处不抛出异常，继续执行后面的代码
            log.error("redis服务器异常" + ExceptionUtils.getStackTrace(e));
        }
        log.info("从数据库中取值");
        dictList = baseMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
        dictList.forEach(dict -> {
            //如果有子节点，则是非叶子节点
            boolean hasChildren = this.hasChildren(dict.getId());
            dict.setHasChildren(hasChildren);
        });
        //将数据存入redis
        try {
            redisTemplate.opsForValue().set("srb:core:dictList:" + parentId, dictList, 5, TimeUnit.MINUTES);
            log.info("数据存入redis");
        }catch (Exception e) {
            //此处不抛出异常，继续执行后面的代码
            log.error("redis服务器异常" + ExceptionUtils.getStackTrace(e));
        }
        return dictList;
    }
    
    /**
     * 根据编码获取数据字典
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        
        return this.listByParentId(dict.getId());
    }
    
    /**
     * 根据 字典信息进行以下操作
     *  计算下拉列表选中内容：学历、行业、月收入、还款来源、联系人关系
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code", dictCode);
        Dict parentDict = baseMapper.selectOne(dictQueryWrapper);
       
        if(parentDict == null) {
            return "";
        }
       
        dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", parentDict.getId()).eq("value", value);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
       
        if(dict == null) {
            return "";
        }
      
        return dict.getName();
    }
    
    
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        if (count.intValue() > 0) {
            return true;
        }
        return false;
    }
}
